package com.huawei.csi.tool.service;

import com.google.common.collect.Lists;
import com.google.gson.reflect.TypeToken;
import com.huawei.csi.tool.domain.Project;
import com.huawei.csi.tool.util.AlphanumComparator;
import com.huawei.csi.tool.util.FileUtil;
import com.huawei.csi.tool.util.OSUtil;
import javafx.concurrent.Task;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Type;
import java.util.List;
import java.util.Optional;

/**
 * @author lxw
 */
public class LoadCJProjectTask extends Task<List<Project>> {
    @Override
    protected List<Project> call() {
        Type type = new TypeToken<List<Project>>() {
        }.getType();
        Optional<Object> objectOptional = FileUtil.jsonFile2Class("data/cj_project.json", type);
        if (objectOptional.isPresent()) {
            updateProgress(1, 1);
            List<Project> projectList = (List<Project>) objectOptional.get();
            if (OSUtil.isEnglish()) {
                projectList = projectList.stream().filter(item -> !"zh-cn-webpage".equalsIgnoreCase(item.getType())).toList();
            }
            projectList.sort((p1, p2) -> {
                if (p1.getType().equalsIgnoreCase(p2.getType())) {
                    return new AlphanumComparator().compare(p1.getName(), p2.getName());
                } else {
                    return p1.getType().compareTo(p2.getType());
                }
            });
            return projectList;
        }
        return Lists.newArrayList();
    }
}
